﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;

namespace pngpacker
{
	public partial class Form2 : Form
	{
		private LinkedList<string> fileList;

		public LinkedList<string> Files
		{
			set
			{
				fileList = value;
			}
		}

		public Form2()
		{
			InitializeComponent();
		}

		private void Form2_Load(object sender, EventArgs e)
		{
			FileInfo file = new FileInfo(fileList.First.Value);
			string dir = file.DirectoryName;
			if (!dir.EndsWith(@"\"))
			{
				dir += @"\";
			}
			textBox1.Text = dir + DateTime.Now.ToString("yyyyMMddhhmmss") + ".png";
			progressBar1.Visible = false;
		}

		private void button1_Click(object sender, EventArgs e)
		{
			if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
			{
				return;
			}
			textBox1.Text = saveFileDialog1.FileName;
		}

		private void button2_Click(object sender, EventArgs e)
		{
			button2.Enabled = false;
			progressBar1.Visible = true;
			updateProgress(0);
			Image[] images = new Image[fileList.Count];
			int i = 0;
			foreach (string file in fileList)
			{
				Image image = null;
				try
				{
					updateProgress((i * 75) / fileList.Count);
					image = Image.FromFile(file);
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return;
				}
				images[i++] = image;
			}
			ImageWorker.MergeOption option = ImageWorker.MergeOption.Horizontal;
			if (radioButton2.Checked)
			{
				option = ImageWorker.MergeOption.Vertical;
			}
			if (checkBox1.Checked)
				option |= ImageWorker.MergeOption.Transparent;
			if (checkBox2.Checked)
				option |= ImageWorker.MergeOption.MaxSize;
			Bitmap merged = ImageWorker.Merge(images, option);
			updateProgress(95);
			//merged.MakeTransparent();
			string filename = textBox1.Text;
			ImageFormat format = ImageFormat.Png;
			if (filename.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
				format = ImageFormat.Png;
			else if (filename.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase))
				format = ImageFormat.Bmp;
			else if (filename.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase))
				format = ImageFormat.Jpeg;
			merged.Save(filename, format);
			foreach (Image image in images)
			{
				image.Dispose();
			}
			merged.Dispose();
			updateProgress(100);
			button2.Enabled = true;
			MessageBox.Show("Completed!", "Export");
			this.Close();
		}

		private void updateProgress(int progress)
		{
			progressBar1.Value = progress;
			progressBar1.Update();
			//Application.DoEvents();
		}
	}
}
